package com.kctvjeju.web.common.util;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class LoginInterceptor extends HandlerInterceptorAdapter {
	protected final Log logger = LogFactory.getLog(getClass());

	private ArrayList<String> methodList = null;
	private ArrayList<String> urlList = null;

	public LoginInterceptor() {
		urlList = new ArrayList<String>();
		methodList = new ArrayList<String>();
		setUrlList();
		setMethodList();
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		if (logger.isDebugEnabled()) {
			logger.debug("### LoginInterceptor 호출 ###");
		}

		/*
		HttpSession session = request.getSession();

		// 관리자 URL 확인
		if ((getCheckExceptionUrl(request.getRequestURL().toString()) || getCheckExceptionMethod(request
				.getRequestURL().toString()))) {

			if (session.getAttribute("LoginInfo") == null) {
				logger.info("로그인 정보가 존재하지 않습니다.");
				session.setAttribute("currentPage", "/admin");
				response.sendRedirect(request.getContextPath() + "/member");
				return false;
			}

			// 권한에 따른 메뉴 접근여부 확인. by Add seorang, 2013.01.29
			if (session != null && session.getAttribute("LoginInfo") != null) {
				LoginDTO loginInfo = (LoginDTO) session
						.getAttribute("LoginInfo");
				if (!loginInfo.getAuthority().equals("0")) {
					logger.info("NOT ACCESS Administrator (id - "
							+ loginInfo.getId() + ")");
					response.sendRedirect(request.getContextPath() + "/main");
					return false;
				}
			}
		}
 */

		if (logger.isDebugEnabled()) {
			logger.debug("### LoginInterceptor 확인 ###");
		}
		return true;
	}

	/**
	 * 예외 메소드 체크
	 * 
	 * @param requestUrl
	 * @return
	 */
	private boolean getCheckExceptionMethod(String requestUrl) {
		boolean flag = false;
		for (String method : methodList) {
			if (requestUrl.lastIndexOf(method) > -1) {
				flag = true;
				break;
			}
		}
		return flag;
	}

	/**
	 * 예외 URL 체크
	 * 
	 * @param requestUrl
	 * @return
	 */
	private boolean getCheckExceptionUrl(String requestUrl) {
		boolean flag = false;
		for (String url : urlList) {
			if (requestUrl.indexOf(url) > -1) {
				flag = true;
				break;
			}
		}
		return flag;
	}

	public ArrayList<String> getUrlList() {
		return urlList;
	}

	public ArrayList<String> getMethodList() {
		return methodList;
	}

	public void setUrlList() {
		// urlList.add(관련 URL);
		methodList.add("/admin/");
	}

	public void setMethodList() {
		methodList.add("/admin");
	}

}
